<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addRole(1,'0')">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addRole(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editRole(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delRole(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 放置一个弹层 用来编辑新增节点  v-if="showDialog" -->
      <el-dialog
        :title="isEdit ?'编辑权限点':'新增权限点'"
        :visible="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="btnCancel"
      >
        <!-- 表单 -->
        <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" style="width:90%" />
          </el-form-item>
          <el-form-item label="开启">
            <el-switch
              v-model="formData.enVisible"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" type="primary" @click="addOrEditPermission">确定</el-button>
            <el-button size="small" @click="btnCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, updatePermission, getPermissionDetail, delPermission } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 校验权限名称
    const validName = (rule, value, callback) => {
      // 获取所有的同级名称
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(item => item.name).includes(value) ? callback(new Error(`${value} 已存在`)) : callback()
    }

    // 校验标识名称 所有的标识都不能重复
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(item => item.code).includes(value) ? callback(new Error(`${value} 已存在`)) : callback()
    }
    return {
      permissionList: [], // 权限列表
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isEdit: false, // 是否是编辑
      originList: [] // 格式化好的数据
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 添加权限
    async addPermission() {
      this.isEdit = false

      const res = await addPermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()
    },
    // 编辑权限
    async editPermission() {
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()
    },

    // 添加或编辑 确定按钮
    addOrEditPermission() {
      this.$refs.perForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editPermission() : this.addPermission()
      })
    },
    // 取消
    btnCancel() {
      this.formData = {
        formData: {
          name: '', // 名称
          code: '', // 权限标识
          description: '', // 描述
          enVisible: '0', // 开启
          pid: '', // 添加到哪个节点下
          type: '' // 类型
        }
      }
      // 重置所有数据
      // 重置编辑
      this.isEdit = false
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },

    // 添加
    addRole(type, id) {
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = id
    },

    // 编辑
    async editRole(id) {
      this.showDialog = true
      this.isEdit = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
    },

    // 删除权限
    async delRole(id) {
      //
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message.info('取消删除')
      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    },

    // 获取权限列表数据
    async getPermissionList() {
      const res = await getPermissionList()
      // this.permissionList = res.data
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
      this.permissionList = tranListToTreeData(res.data, '0')
    }
  }
}
</script>

<style lang="scss" scoped></style>
